/*
 * @FileName: [ResourceController.java]
 * 
 * @Package com.bcinfo.upp.admin.ac.controller
 * 
 * 
 * Copyright (c) 2011-2015 BCINFO Technology Limited Com. All rights reserved.
 * 
 * This software is the confidential and proprietary information of BCINFO
 * Technology Limited Company ("Confidential Information"). You shall not
 * disclose such Confidential Information and shall use it only in accordance
 * with the terms of the contract agreement you entered into with RKY.
 * 
 * $Rev: 42 $ $LastChangedDate: 2013-10-12 10:19:36 +0800 (星期六, 12 十月 2013) $
 * $LastChangedBy: wanggc $
 * 
 * @category bcinfo-upp
 * 
 * @version 1.1
 * 
 * @author $Author: wanggc $
 * 
 * Change History:[Formatter: author date description] <br/> 1 2 3
 */

package com.bcinfo.iccard.admin.ac.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.bcinfo.iccard.admin.common.Constants;
import com.bcinfo.iccard.admin.common.ModuleEnum;
import com.bcinfo.iccard.admin.controller.AbstractController;
import com.bcinfo.upp.ac.model.Resource;
import com.bcinfo.upp.ac.model.ResourceAction;
import com.bcinfo.upp.ac.model.RolePermission;
import com.bcinfo.upp.ac.service.PermissionService;
import com.bcinfo.upp.ac.service.ResourceService;
import com.bcinfo.upp.ac.util.PermissionUtil;
import com.bcinfo.upp.exception.InvalidParametersException;
import com.bcinfo.upp.exception.UppDataBaseException;

/**
 * 权限控制 <br/>
 * <p>
 * Description:<br/>
 * <p>
 * 
 * 
 * <p>
 * For Examples <br/>
 * 
 * <PRE>
 * 
 * </PRE>
 * <p>
 */
@Controller
@RequestMapping("/ac/acresource")
public class ACResourceController extends AbstractController
{
    private final static Logger _logger = Logger.getLogger(ACResourceController.class);

    @Autowired()
    private ResourceService     _resourceService;

    @Autowired()
    private PermissionService   _permissionService;

    /**
     * 
     * 
     * 过滤权限action 列表，只保留角色拥有的 <br/>
     * <p>
     * <br/>
     * <p>
     * Author: chenyc<br/>
     * <p>
     * Date: 2013-5-4-上午09:55:39<br/>
     * <p>
     * 
     * @return
     * 
     */
    private List<ResourceAction> filtorActins(List<ResourceAction> allaction, long actions)
    {

        for (Iterator<ResourceAction> iterator = allaction.iterator(); iterator.hasNext();)
        {
            ResourceAction resourceAction = (ResourceAction) iterator.next();
            if (!PermissionUtil.hasPermission(actions, resourceAction.getBitwiseValue()))
            {
                iterator.remove();
            }

        }
        return allaction;
    }

    /**
     * 
     * 跳转到页面展示所有资源权限，报错和某个角色是否具有某个资源的操作权限的展示信息 <br/>
     * <p>
     * <br/>
     * <p>
     * Author: chenyc<br/>
     * <p>
     * Date: 2013-4-26-下午04:49:30<br/>
     * <p>
     * 
     * @param request
     * @return
     * 
     */
    @SuppressWarnings("unchecked")
    @RequestMapping("/toListView")
    public ModelAndView toList(HttpServletRequest request)
    {
        ModelAndView mv = new ModelAndView("ac/acresource/acresource_list");
        try
        {
            // 登录者拥有的角色权限
            Map<Long, RolePermission> loginRolesPermissionMap = (Map<Long, RolePermission>) request.getSession()
                    .getAttribute(Constants.CURRENT_ROLE_PERMISSION);

            List<Resource> reses = null;

            if (this.getCurrentOperator().getOwner() == -1)
            {// 超级管理员

                reses = _resourceService.listFunctions();
            }
            else
            {
                // 获取登录者拥有的角色权限资源
                reses = new ArrayList<Resource>();
                Set<Long> keys = loginRolesPermissionMap.keySet();
                for (Object k : keys)
                {
                    try
                    {
                        RolePermission rolepermission = loginRolesPermissionMap.get(k);
                        Resource r = rolepermission.getResource();
                        List<ResourceAction> allaction = r.getResType().getResourceActions();
                        // 过滤，只保留当前用户拥有的权限
                        r.getResType().setResourceActions(this.filtorActins(allaction, rolepermission.getActions()));
                        reses.add(r);
                    }
                    catch (NumberFormatException e)
                    {
                        _logger.error(ExceptionUtils.getStackTrace(e));
                        addLog(ModuleEnum.AcResource.view, "operatorId=" + getOperatorId() + "|desc=查询资源及权限权限失败");
                    }
                }

            }

            // 被编辑的角色拥有的角色权限
            String roleIdstr = request.getParameter("roleId");
            if (!StringUtils.isEmpty(roleIdstr))
            {
                long roleId = Long.parseLong(roleIdstr);
                List<RolePermission> permissiones = null;
                try
                {
                    permissiones = _permissionService.listRolePermissionsByRole(roleId);
                }
                catch (InvalidParametersException e)
                {
                    _logger.error(ExceptionUtils.getStackTrace(e));
                    addLog(ModuleEnum.AcResource.view, "operatorId=" + getOperatorId() + "|desc=查询资源及权限权限失败");
                }

                Map<Long, Long> m = new HashMap<Long, Long>();
                for (RolePermission rolePermission : permissiones)
                {
                    m.put(rolePermission.getResourceId(), rolePermission.getActions());
                }

                mv.addObject("res_action_map", m);

                mv.addObject("permissiones", permissiones);
            }
            addLog(ModuleEnum.AcResource.view, "operatorId=" + getOperatorId() + "|desc=查询资源成功");

            // 按照菜单分组展示，将资源列表放到map，便于获取

            Map<Long, Resource> mapres = new HashMap<Long, Resource>();
            for (Resource resource : reses)
            {
                mapres.put(Long.parseLong(resource.getPrimkey()), resource);
            }
            mv.addObject("mapres", mapres);
            // mv.addObject("reses", reses);
        }
        catch (UppDataBaseException e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
            addLog(ModuleEnum.AcResource.view, "operatorId=" + getOperatorId() + "|desc=查询资源及权限权限失败");
        }

        return mv;
    }

    /*
     * (non-Javadoc) Description: <br/>
     * 
     * @return
     * 
     * @see com.bcinfo.upp.admin.controller.AdminController#getMouduleCode()
     */
    @Override
    public String getMouduleCode()
    {
        return ModuleEnum.AcResource.moduleName.value;
    }
}